package com.msxt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msxt.dto.ChatMessage;
import com.msxt.dto.ZaixiankefuDTO;
import com.msxt.dto.ZaixiankefuEntity;
import com.msxt.mapper.ZaixiankefuDao;
import com.msxt.result.Query;
import com.msxt.service.ZaixiankefuService;
import com.msxt.utils.PageUtils;
import com.msxt.view.ZaixiankefuView;
import com.msxt.vo.ZaixiankefuVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Service("zaixiankefuService")
public class ZaixiankefuServiceImpl extends ServiceImpl<ZaixiankefuDao, ZaixiankefuEntity> implements ZaixiankefuService {

	@Autowired
	private ZaixiankefuDao zaixiankefuDao;

	@Override
	@Transactional
	public ZaixiankefuDTO getZaixiankefuDetailWithMessages(Long id) {
		// 先设置 group_concat_max_len
		zaixiankefuDao.setGroupConcatMaxLen(1000000);

		// 然后执行查询
		ZaixiankefuDTO dto = zaixiankefuDao.selectZaixiankefuWithMessages(id);

		if (dto != null) {
			List<ChatMessage> allMessageList = new ArrayList<>();

			// 1. 添加咨询内容（用户消息）
			if (StringUtils.isNotBlank(dto.getZNeirong())) {
				ChatMessage userMsg = new ChatMessage();
				userMsg.setContent(dto.getZNeirong().trim());
				userMsg.setSenderType("user");
				userMsg.setTimestamp(dto.getZNeirongTime() != null ?
						dto.getZNeirongTime() :
						dto.getAddtime() != null ? dto.getAddtime().getTime() : System.currentTimeMillis());
				userMsg.setSenderName(dto.getYonghuxingming() != null ?
						dto.getYonghuxingming() : "用户");
				allMessageList.add(userMsg);
			}

			// 2. 添加商家回复
			if (StringUtils.isNotBlank(dto.getZShhf())) {
				ChatMessage merchantMsg = new ChatMessage();
				merchantMsg.setContent(dto.getZShhf().trim());
				merchantMsg.setSenderType("merchant");
				merchantMsg.setTimestamp(dto.getZShhfTime() != null ?
						dto.getZShhfTime() :
						dto.getAddtime() != null ? dto.getAddtime().getTime() + 60000 : System.currentTimeMillis() + 60000);
				merchantMsg.setSenderName(dto.getShangjiamingcheng() != null ?
						dto.getShangjiamingcheng() : "商家");
				allMessageList.add(merchantMsg);
			}

			// 3. 添加聊天消息表中的消息
			processMessages(dto, allMessageList);

			// 按时间戳排序
			allMessageList.sort(Comparator.comparing(ChatMessage::getTimestamp));

			// 设置按时间排序的所有消息
			dto.setAllMessages(allMessageList.toArray(new ChatMessage[0]));

			// 同时保持原有的userMessages和merchantMessages数组（按类型分组）
			List<String> userMessagesList = new ArrayList<>();
			List<String> merchantMessagesList = new ArrayList<>();

			for (ChatMessage message : allMessageList) {
				if ("user".equals(message.getSenderType())) {
					userMessagesList.add(message.getContent());
				} else if ("merchant".equals(message.getSenderType())) {
					merchantMessagesList.add(message.getContent());
				}
			}

			dto.setUserMessages(userMessagesList.toArray(new String[0]));
			dto.setMerchantMessages(merchantMessagesList.toArray(new String[0]));

			// 记录日志用于调试
			log.info("消息合并结果 - ID: {}", id);
			log.info("按时间排序的消息数量: {}", allMessageList.size());
			for (ChatMessage message : allMessageList) {
				log.info("消息 - 发送者: {}, 时间: {}, 内容: {}",
						message.getSenderType(), message.getTimestamp(), message.getContent());
			}
		}

		return dto;
	}

	private void processMessages(ZaixiankefuDTO dto, List<ChatMessage> allMessageList) {
		// 处理用户消息
		if (StringUtils.isNotBlank(dto.getChatUserMessages())) {
			String[] messages = dto.getChatUserMessages().split("\\|\\|\\|");
			for (String msg : messages) {
				if (StringUtils.isNotBlank(msg)) {
					ChatMessage cm = createMessage("user", msg, dto);
					allMessageList.add(cm);
				}
			}
		}

		// 处理商家消息
		if (StringUtils.isNotBlank(dto.getChatMerchantMessages())) {
			String[] messages = dto.getChatMerchantMessages().split("\\|\\|\\|");
			for (String msg : messages) {
				if (StringUtils.isNotBlank(msg)) {
					ChatMessage cm = createMessage("merchant", msg, dto);
					allMessageList.add(cm);
				}
			}
		}
	}


	@Override
	public Long count(QueryWrapper<ZaixiankefuEntity> wrapper) {
		return baseMapper.selectCount(wrapper);
	}

	private ChatMessage createMessage(String senderType, String content, ZaixiankefuDTO dto) {
		ChatMessage message = new ChatMessage();
		message.setContent(content.trim());
		message.setSenderType(senderType);

		// 使用实际时间戳（如果无法获取则使用默认值）
		long baseTime = dto.getAddtime() != null ? dto.getAddtime().getTime() : System.currentTimeMillis();
		if ("user".equals(senderType)) {
			message.setTimestamp(baseTime + 120000); // 用户消息在咨询后2分钟
			message.setSenderName(dto.getYonghuxingming() != null ?
					dto.getYonghuxingming() : "用户");
		} else {
			message.setTimestamp(baseTime + 180000); // 商家消息在咨询后3分钟
			message.setSenderName(dto.getShangjiamingcheng() != null ?
					dto.getShangjiamingcheng() : "商家");
		}
		return message;
	}

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		QueryWrapper<ZaixiankefuEntity> wrapper = new QueryWrapper<>();
		// 处理排序参数
		String sort = (String) params.get("sort");
		String order = (String) params.get("order");
		if (StringUtils.isNotBlank(sort)) {
			boolean isAsc = "asc".equalsIgnoreCase(order);
			wrapper.orderBy(true, isAsc, sort);
		}

		// 处理查询条件
		params.forEach((key, value) -> {
			if (value != null && !key.equals("page") && !key.equals("limit")
					&& !key.equals("sort") && !key.equals("order")) {
				wrapper.eq(key, value);
			}
		});

		Page<ZaixiankefuEntity> page = this.page(
				new Query<ZaixiankefuEntity>(params).getPage(),
				wrapper
		);
		return new PageUtils(page);
	}

	@Override
	public PageUtils queryPage(Map<String, Object> params, QueryWrapper<ZaixiankefuEntity> wrapper) {
		try {
			// 处理分页参数，添加默认值保障
			long pageNum = 1;
			long pageSize = 10;

			if (params.containsKey("page")) {
				Object pageParam = params.get("page");
				if (pageParam != null) {
					pageNum = Long.parseLong(pageParam.toString());
					if (pageNum < 1) pageNum = 1;
				}
			}

			if (params.containsKey("limit")) {
				Object limitParam = params.get("limit");
				if (limitParam != null) {
					pageSize = Long.parseLong(limitParam.toString());
					if (pageSize < 1) pageSize = 10;
					if (pageSize > 1000) pageSize = 1000;
				}
			}

			// 其他逻辑保持不变...
			if (params.containsKey("sort") && params.containsKey("order")) {
				String sort = params.get("sort").toString();
				String order = params.get("order").toString();
				boolean isAsc = "asc".equalsIgnoreCase(order);
				if (StringUtils.isNotBlank(sort)) {
					wrapper.orderBy(true, isAsc, sort);
				}
			}

			// 处理区间查询
			if (params.containsKey("start") && params.containsKey("end")) {
				String start = params.get("start").toString();
				String end = params.get("end").toString();
				if (StringUtils.isNotBlank(start) && StringUtils.isNotBlank(end)) {
					wrapper.between("create_time", start, end);
				}
			}

			// 创建分页对象
			Page<ZaixiankefuEntity> page = new Page<>(pageNum, pageSize);
			IPage<ZaixiankefuEntity> result = baseMapper.selectPage(page, wrapper);
			return new PageUtils(result);

		} catch (NumberFormatException e) {
			log.error("分页参数格式错误: {}", params, e);
			Page<ZaixiankefuEntity> defaultPage = new Page<>(1, 10);
			IPage<ZaixiankefuEntity> result = baseMapper.selectPage(defaultPage, wrapper);
			return new PageUtils(result);
		}
	}


	@Override
	public List<ZaixiankefuVO> listVO(QueryWrapper<ZaixiankefuEntity> wrapper) {
		return baseMapper.listVO(wrapper);
	}

	@Override
	public ZaixiankefuVO selectVO(QueryWrapper<ZaixiankefuEntity> wrapper) {
		return baseMapper.selectVO(wrapper);
	}

	@Override
	public List<ZaixiankefuView> listView(QueryWrapper<ZaixiankefuEntity> wrapper) {
		return baseMapper.listView(wrapper);
	}

	@Override
	public ZaixiankefuView selectView(QueryWrapper<ZaixiankefuEntity> wrapper) {
		return baseMapper.selectView(wrapper);
	}

	@Override
	public boolean save(ZaixiankefuEntity entity) {
		if (entity.getBianhao() == null) {
			entity.setBianhao(generateUniqueBianhao());
		}
		return super.save(entity);
	}

	private String generateUniqueBianhao() {
		long timestamp = System.currentTimeMillis();
		return String.format("%010d", timestamp % 10000000000L);
	}
}